package com.example.admin.controller;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.example.admin.entity.SysLogininfor;
import com.example.util.address.AddressUtils;
import com.example.util.address.IpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.admin.entity.CommonUser;
import com.example.admin.entity.SysUser;
import com.example.shrio.conf.CustomizedToken;
import com.example.util.APIState;
import com.example.util.AjaxResult;
import com.example.shrio.CurrentUser;
import com.example.shrio.LoginType;
import com.example.util.redis.RedisKeys;

import javax.servlet.http.HttpServletRequest;

/**
 * @author wangkai
 * @date: 2019年6月4日 下午2:42:15
 */
@RestController
@Api(value = "后台登录Controller", tags = {"后台登录操作接口" })
@RequestMapping(value = "/admin/home")
public class HomeController {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 登陆
     *
     * @param account
     * @param password
     * @return
     */
    @ApiOperation(value = "后台登录", httpMethod = "POST")
    @PostMapping(value = "/login")
    public AjaxResult login(HttpServletRequest request, String account, String password) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (account != null && password != null) {
            CustomizedToken token = new CustomizedToken(account, password, LoginType.ADMIN.toString());
            Subject subject = CurrentUser.getSubject();
            subject.login(token);
            Map<String, Object> m = new HashMap<>();
            SysUser user = CurrentUser.getAdminUser();
            Serializable sessionId = subject.getSession().getId();
//            m.put("user", user);
            m.put("token", sessionId);
            result.put("data", m);
            redisTemplate.opsForValue().set(RedisKeys.getShiroSysUserTokenKey(sessionId.toString()), user.getAccount(),
                    30, TimeUnit.MINUTES);
            redisTemplate.opsForValue().set(RedisKeys.getShiroSysUserKey(user.getAccount()), sessionId, 30,
                    TimeUnit.MINUTES);
            createLog(user.getAccount(), "登陆成功", request);
            return new AjaxResult(APIState.S00, "登陆成功", result);
        }
        createLog(account, "登陆失败", request);
        return new AjaxResult(APIState.S01, "用户名或密码未填");
    }

    @ApiOperation(value = "前端登录", httpMethod = "POST")
    @PostMapping(value = "/common/login")
    public AjaxResult ulogin(String account, String password) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (account != null && password != null) {
            CustomizedToken token = new CustomizedToken(account, password, LoginType.USER.toString());
            Subject subject = CurrentUser.getSubject();
            subject.login(token);
            Map<String, Object> m = new HashMap<>();
            CommonUser user = CurrentUser.getCommonUser();
            Serializable sessionId = subject.getSession().getId();
            m.put("user", user);
            m.put("token", sessionId);
            result.put("data", m);
            redisTemplate.opsForValue().set(RedisKeys.getShiroCommonUserTokenKey(sessionId.toString()), user.getAccount(),
                    30, TimeUnit.MINUTES);
            redisTemplate.opsForValue().set(RedisKeys.getShiroCommonUserKey(user.getAccount()), sessionId, 30,
                    TimeUnit.MINUTES);
            return new AjaxResult(APIState.S00, "登陆成功", result);
        }
        return new AjaxResult(APIState.S01, "用户名或密码未填");
    }

    /**
     * 登出
     *
     * @return
     */
    @ApiOperation(value = "登出", httpMethod = "GET")
    @GetMapping(value = "/logout")
    public AjaxResult logout(HttpServletRequest request) {
        SysUser sysUser = CurrentUser.getAdminUser();
        String key = RedisKeys.getShiroSysUserTokenKey(CurrentUser.getSession().getId().toString());
        String userKay = RedisKeys.getShiroSysUserKey(sysUser.getAccount());
        redisTemplate.delete(key);
        redisTemplate.delete(userKay);
        CurrentUser.logout();
        createLog(sysUser.getAccount(), "登出成功", request);
        return new AjaxResult(APIState.S00, "登出成功");
    }


    private void createLog(String userName, String msg, HttpServletRequest request) {
        SysLogininfor sysLoginInfo = new SysLogininfor();
        sysLoginInfo.setIpaddr(IpUtils.getIpAddr(request));
        sysLoginInfo.setLoginLocation(AddressUtils.getRealAddressByIP(sysLoginInfo.getIpaddr()));
        sysLoginInfo.setLoginTime(new Date());
        sysLoginInfo.setStatus("0");
        sysLoginInfo.setMsg(msg);
        sysLoginInfo.setUserName(userName);
        Map<String, String> map = IpUtils.getOsAndBrowserInfo(request);
        sysLoginInfo.setOs(map.get("os"));
        sysLoginInfo.setBrowser(map.get("browser"));
        sysLoginInfo.insert();
    }

}
